<script>
    import { BeButton, BeForm, BeFormItem, BeInput } from '@brewer/beerui';
    import { random } from '../js/utils';
    import { onDestroy } from 'svelte'

    export let speed;
    export let manual;

    let Hlist = [];
    let hIndex = -1;
    let timer = null;
    let cur = ''
    let min = 10
    let max = 100

    $: cur = Hlist[hIndex] || ''

    let resEl;

    function pushRes(n) {
        if (Hlist.length >= 10) {
            Hlist.shift();
            Hlist = Hlist;
        }
        Hlist.push(n);
    }
    function action() {
        console.log(manual)
        if (hIndex === Hlist.length - 1) {
            let inner;
            inner = random(min, max);
            pushRes(inner);
            hIndex = Hlist.length - 1;
        } else {
            hIndex += 1;
        }

        if (manual) {
            return false;
        }
        clearTimeout(timer);
        timer = setTimeout(function () {
            action();
        }, speed * 1000);
    }
    // action()

    const play = () => {
        manual = false;
        action();
    };

    const prev = () => {
        clearTimeout(timer);
        if (hIndex <= -1) {
            hIndex = Hlist.length - 1;
        } else if (hIndex > 0) {
            hIndex -= 1;
        }
    };

    const next = () => {
        clearTimeout(timer);
        action();
    };

    function numKeyDown(ev){
        if (ev.keyCode === 13 || ev.key === 'Enter') {
            clearTimeout(timer);
            action();
        } else if (ev.keyCode === 8 || ev.key === 'Backspace') {
            prev();
        }
    }
    document.addEventListener('keydown', numKeyDown);

    onDestroy(()=>{
        document.removeEventListener('keydown', numKeyDown);
        clearTimeout(timer);
    })
</script>

<div class="number">
    <div class="num_ctrl">
        <BeForm labelWidth="130px">
            <BeFormItem label="最小数：">
                <BeInput type="number" size="small" bind:value={min} />
            </BeFormItem>
            <BeFormItem label="最大数：">
                <BeInput type="number" size="small" bind:value={max} />
            </BeFormItem>
        </BeForm>
        <div style="margin-top: 20px;">
            <BeButton size="small" style="margin-left:40px" on:click={play}>开始播放</BeButton>
        </div>
    </div>
    <div class="num" bind:this={ resEl }>
        <span class="n_p">{cur || '未开始'}</span>
    </div>
    <div class="tc">
        <BeButton class="prev" size="mini" on:click={prev}>上一个</BeButton>（退格/删除键）
        <BeButton class="next" size="mini" on:click={next}>下一个</BeButton>（回车键）
        <BeButton class="next" size="mini" on:click={resEl.requestFullscreen()}>全屏</BeButton>
    </div>
</div>

<style>
    
</style>
